//
//  LZFAddTagController.m
//  LZFBuDieJie
//
//  Created by 梁梓烽 on 16/7/8.
//  Copyright © 2016年 liangzifeng. All rights reserved.
//

#import "LZFAddTagController.h"
#import "UITextField+Placeholder.h"
#import "LZFTagButton.h"
#import "LZFTagTextField.h"
#import <SVProgressHUD.h>

@interface LZFAddTagController ()<UITextFieldDelegate>
/** contentView */
@property(nonatomic,weak)UIView *contentView;
@property(nonatomic,weak)UITextField *textFiled;
@property(nonatomic,weak)UIButton *tipButton;
@property(nonatomic,strong)NSMutableArray<LZFTagButton *> *tagButtons;
@end

@implementation LZFAddTagController

#pragma  mark 懒加载
-(NSMutableArray<LZFTagButton *> *)tagButtons{
    if (_tagButtons==nil) {
        _tagButtons=[NSMutableArray new];
    }
    return _tagButtons;
}

-(UIButton *)tipButton
{
    if (_tipButton==nil) {
        UIButton *tipButton=[UIButton buttonWithType:UIButtonTypeCustom];
        [tipButton addTarget:self action:@selector(tipClick) forControlEvents:UIControlEventTouchUpInside];
        tipButton.xmg_width=self.contentView.xmg_width;
        tipButton.xmg_height=LZFTagButtonHeight;
        tipButton.xmg_x=0;
        tipButton.backgroundColor=[UIColor blueColor];
        tipButton.titleLabel.font=[UIFont systemFontOfSize:14];
        tipButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
        tipButton.contentEdgeInsets=UIEdgeInsetsMake(0, LZFSmallMargin, 0, 0);
        [self.contentView addSubview:tipButton];
        _tipButton=tipButton;
    }
    return _tipButton;
}


#pragma mark -初始化
-(void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    [self setUpNav];
    [self setUpContentView];
    [self setupTextField];
    [self setupTags];
}

-(void)setUpNav
{
    self.title = @"添加标签";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(done)];
    
}

-(void)setUpContentView
{
    UIView *contentView=[[UIView alloc]init];
//    contentView.backgroundColor=[UIColor redColor];
    contentView.xmg_x=LZFSmallMargin;
    contentView.xmg_y=LZFNavMaxY+LZFSmallMargin;
    contentView.xmg_width=self.view.xmg_width-2*LZFSmallMargin;
    contentView.xmg_height=self.view.xmg_height;
    _contentView=contentView;
    [self.view addSubview:contentView];
}

-(void)setupTextField
{
    WeakSelf;
    LZFTagTextField *textField=[[LZFTagTextField alloc]init];
    _textFiled=textField;
    [self.contentView addSubview:textField];
    textField.xmg_width=self.contentView.xmg_width;
    textField.xmg_height=LZFTagButtonHeight;
    
    [textField addTarget:self action:@selector(textDidChange) forControlEvents:UIControlEventEditingChanged];
    textField.placeholder=@"多个标签用逗号或者换行隔开";
    textField.placeholderColor=[UIColor grayColor];
    textField.delegate=self;
   
    //设置点击删除按钮需要执行的操作
    textField.deleteBackwardOperation=^{
        
        if (weakSelf.textFiled.hasText||weakSelf.tagButtons.count==0) return ;
        
        // 点击了最后一个标签按钮（删掉最后一个标签按钮）
        [weakSelf tagClick:weakSelf.tagButtons.lastObject];
    };
}


-(void)setupTags
{
    for (NSString *tag in self.tags) {
        self.textFiled.text=tag;
        [self tipClick];
    }
}


#pragma mark -监听
/** 监听textFiled文字的改变 */
-(void)textDidChange
{
    
    if (self.textFiled.hasText) {
        //有文字
        NSString *text=self.textFiled.text;
        NSString *lastStr=[text substringToIndex:text.length-1];

        if ([lastStr isEqualToString:@","]||[lastStr isEqualToString:@","])
          {
            //输入最后的字符是逗号
            //删除最后的逗号
            [self.textFiled deleteBackward];
            //模拟点击一下tipButton
              [self tipClick];
          }
        
        else
         {//输入最后的字符不是逗号
             
             //设置textField的frame
             [self setUpTextFieldFrame];
             
             //设置tipButton的文字
             self.tipButton.hidden=NO;
             [self.tipButton setTitle:[NSString stringWithFormat:@"添加标签：%@",text] forState:UIControlStateNormal];
         }
      }
    else
    {
        //无文字
        self.tipButton.hidden=YES;
    }
}

/** 点击了tipButton */

-(void)tipClick
{
    if (self.textFiled.hasText==NO) return;
    
    if (self.tagButtons.count==5) {
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        [SVProgressHUD showErrorWithStatus:@"最多天机5个标签"];
        return;
    }
    
    //创建一个标签按钮
    LZFTagButton *newTagButton=[[LZFTagButton alloc]init];
    [newTagButton addTarget:self action:@selector(tagClick:) forControlEvents:UIControlEventTouchUpInside];
    [newTagButton setTitle:self.textFiled.text forState:UIControlStateNormal];
    [self.contentView addSubview:newTagButton];
    
    //设置位置-参照最后一个标签那妞
    [self setTagButtonFrame:newTagButton referenceButton:[self.tagButtons lastObject]];
    
    //把newTagButton添加到数组中
    [self.tagButtons addObject:newTagButton];
    
    //排布文本框
    self.textFiled.text=nil;
    [self setUpTextFieldFrame];
    
    //隐藏tipButton
    self.tipButton.hidden=YES;
 }

/** 点击取消那妞 */
-(void)cancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


/** 点击完成按钮 */
-(void)done
{
    //传递tabButton的title给上一个界面
    NSArray *tags =[self.tagButtons valueForKeyPath:@"currentTitle"];
    !self.getTagsBlock? : self.getTagsBlock(tags);
    
    //关闭当前控制器
    [self dismissViewControllerAnimated:YES completion:nil];
}


/** 点击了tagButton */
-(void)tagClick:(LZFTagButton *)clickedTagButton
{
    NSInteger index=[self.tagButtons indexOfObject:clickedTagButton];
    [self.tagButtons removeObject:clickedTagButton];
    
    //删除按钮
    [clickedTagButton removeFromSuperview];
    [self.tagButtons removeObject:clickedTagButton];
    
    //处理后面的标签按钮
    for (NSInteger i=index; i<self.tagButtons.count; i++) {
        LZFTagButton *tagButton=self.tagButtons[i];
        LZFTagButton *previousTagButton=(i==0)? nil:self.tagButtons[i-1];
        [self setTagButtonFrame:tagButton referenceButton:previousTagButton];
    }
    
    //排布文本框
    [self setUpTextFieldFrame];
}


#pragma mark -设置控件的frame

/**
 *  设置标签按钮的frame
 *
 *  @param tagButton       需要设置frame的标签按钮
 *  @param referenceButton  计算tagButton按钮的frame的参照按钮
 */
-(void)setTagButtonFrame:(LZFTagButton *)tagButton referenceButton:(LZFTagButton *)referenceButton
{
    if (referenceButton==nil) {
        tagButton.xmg_x=0;
        tagButton.xmg_y=0;
        return;
    }
    
    CGFloat leftWidth=CGRectGetMaxX(referenceButton.frame)+LZFSmallMargin;
    CGFloat rightWidth=self.contentView.xmg_width-leftWidth;
    
    if (rightWidth>tagButton.xmg_width) {
        //不需要换行
        tagButton.xmg_x=leftWidth;
        tagButton.xmg_y=referenceButton.xmg_y;
    }
    
    else
    {
        //需要换行
        tagButton.xmg_x=0;
        tagButton.xmg_y=CGRectGetMaxY(referenceButton.frame)+LZFSmallMargin;
    
    }
}


/**排布textField的frame */
-(void)setUpTextFieldFrame
{
    CGFloat textW=[self.textFiled.text sizeWithAttributes:@{NSFontAttributeName:self.textFiled.font}].width;
    textW =MAX(100, textW);
    
    LZFTagButton *lastButton=[self.tagButtons lastObject];
    if (lastButton==nil) {
        self.textFiled.xmg_x=0;
        self.textFiled.xmg_y=0;
    }
    
     else
     {
         CGFloat leftWidth=CGRectGetMaxX(lastButton.frame)+LZFSmallMargin;
         CGFloat rightWidth=self.contentView.xmg_width-leftWidth;
         if (rightWidth>textW) {
             //textField不用换行
             self.textFiled.xmg_x=leftWidth;
             self.textFiled.xmg_y=[self.tagButtons lastObject].xmg_y;
         }
         
         else
         {
             //textFiled需要换行
             self.textFiled.xmg_x=0;
             self.textFiled.xmg_y=CGRectGetMaxY(lastButton.frame)+LZFSmallMargin;
         }
         
     }

    //排布tipButton
    self.tipButton.xmg_y=CGRectGetMaxY(self.textFiled.frame)+LZFSmallMargin;

    
}



#pragma mark -<UITextFieldDelegate>

/** 点击键盘的return按钮回调的方法 */
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self tipClick];
    return YES;
}


@end
